import axios from 'axios'
import { showNotify } from 'vant'
import { useUserStore } from '@/stores/user'
export default (url, data, method) =>
  new Promise((resolve, reject) => {
    Object.keys(data).forEach((key) => {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        if (data[key] === undefined) {
          data[key] = ''
        }
      }
    })
    if (method === 'get') {
      url += '?'
      Object.keys(data).forEach((key) => {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
          url += `${key}=${data[key]}&`
        }
      })
      url = url.substring(0, url.length - 1)
    }
    const userStore = useUserStore()
    axios({
      url: `${import.meta.env.VITE_RECSTEEL_API_URL}${url}`,
      data,
      method,
      headers: {
        Authorization: userStore.token
      }
    })
      .then((response) => {
        const res = response.data
        if (res.success) {
          resolve(res)
        } else {
          if (res.message) {
            showNotify({
              message: res.message,
              type: 'danger'
            })
          } else {
            showNotify({
              message: '网络波动，请联系管理员',
              type: 'danger'
            })
          }

          // const logoutCodeArr = ['TK01', 'TK02', 'TK03', 'TK04', 'TK05', 'TK06', 'GHJ02']
          reject(res)
        }
      })
      .catch(({ response: res }) => {
        if (res.data.message) {
          showNotify({
            message: res.data.message,
            type: 'danger'
          })
        } else {
          showNotify({
            message: '网络波动，请联系管理员',
            type: 'danger'
          })
        }
        reject(res.data)
      })
      .finally(() => {})
  })
